package gen.tools.squad;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManipulateGridSquad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridSquad() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "";
		final String oper = request.getParameter("oper");						//增刪改查那一種
		final String subsysId = request.getParameter("subsysId");
		final String squadId = request.getParameter("squadId");
		final String squadpath = request.getParameter("squadPath");						//部署班的部署路徑
		String result = "";
		final String empId = request.getParameter("empId");
		
		try {
			conn = wid.getConn();
			/** 判別需進行何種操作 **/
			if ( "del".equalsIgnoreCase(oper) ) {
				/*	刪除資訊群組	*/
				sql = "DELETE FROM squad WHERE subsysid=? AND squadid=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, squadId);
				ps.execute();
				result = "刪除了"+squadId;
			} else if ( "add".equalsIgnoreCase(oper) ) {
				sql = "INSERT INTO squad (subsysId,squadId,squadPath,creatorId,cDT) VALUES (?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, squadId);
				ps.setString(3, squadpath);
				ps.setString(4, empId);
				ps.setTimestamp(5, wid.cDT() );
				ps.execute();
				result = "新增完成 "+squadId;
			} else if ( "edit".equalsIgnoreCase(oper) ) {
				sql = "UPDATE squad SET squadPath=? WHERE subsysId=? AND squadId=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, squadpath);
				ps.setString(2, subsysId);
				ps.setString(3, request.getParameter("id") );
				ps.execute();
				result = "修改完成 "+squadId;
			}
		} catch ( Exception e) {
			result = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if (rs!= null) { rs.close(); }
				if (ps!= null) { ps.close(); }
				if (conn!= null) {conn.close();}
			} catch (SQLException e) { System.out.println(wid.errProcess(e)); }	
		}
		
		response.getWriter().write(result);		
	}

}
